package com.dragon.utilslibrary.dblib.update;

import android.content.Context;

import com.dragon.utilslibrary.dblib.DBConfig;
import com.dragon.utilslibrary.dblib.PrivateDataBaseEnums;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class UpdateManager {
    private File parentFile = new File(PrivateDataBaseEnums.databasefile.getDataBasePath());
    private File bakFile = new File(parentFile, PrivateDataBaseEnums.backDb_file_name.value);
    private DBUpdateManager dbUpdateManager;
    private ClipherDBUpdateManager clipherDBUpdateManager;
    public UpdateManager() {
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        if (!bakFile.exists()) {
            bakFile.mkdirs();
        }
        dbUpdateManager = new DBUpdateManager();
        clipherDBUpdateManager = new ClipherDBUpdateManager();
    }

    /**
     * @param context
     * @param thisDbVersion，当前数据库版本号
     */
    public void checkThisVersionTable(Context context, String thisDbVersion) {
        if ("1".equalsIgnoreCase(DBConfig.encryptionDB)) {
            clipherDBUpdateManager.checkThisVersionTable(context, thisDbVersion);
        } else {
            dbUpdateManager.checkThisVersionTable(context, thisDbVersion);
        }
    }

    /**
     * 开始升级
     *
     * @param context
     */
    public boolean startUpdateDb(Context context, String thisDbVersion) {
        if ("1".equalsIgnoreCase(DBConfig.encryptionDB)) {
            return clipherDBUpdateManager.startUpdateDb(context, thisDbVersion);
        } else {
            return dbUpdateManager.startUpdateDb(context, thisDbVersion);
        }
    }

    /**
     * 保存下载APK版本信息
     *
     * @param context
     * @param locVersion 当前正在运行的版本号，
     * @return
     */
    public boolean saveVersionInfo(Context context, String locVersion) {
        boolean ret = false;

        FileWriter writer = null;
        try {
            writer = new FileWriter(new File(parentFile, "update.txt"), false);
//            writer.write("V003"+ INFO_FILE_DIV +"V002");
            writer.write(locVersion);
            writer.flush();
            ret = true;
        } catch (IOException e) {
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return ret;
    }

}
